var location = require("../../../mybehaviors/location/location");
const app = getApp();
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');
Page({

  behaviors: [location, skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    cate_level:2,
    limit_1km:0,
    second_index: '',
    three_index: "",
    goods_info: {},
    category_list: [],
    second_list: [],
    three_list: [],
    first_index: null,
    category_name: "全部分类",
    nav_flag: false,
    list: [],
    keywords: "",
    parms: {
      1: {
        sort_by: 1,
        order_by: 0
      },
      2: {
        sort_by: 2,
        order_by: 0
      },
      3: {
        sort_by: 3,
        order_by: 0
      }
    },
    cursor: 1,
    point: {},
    citycode: 0,
    sort_by: 0,
    distance_max: 0,
    city_name: "定位",
    options: {},
    first_cate_id: "",
    second_cate_id: "",
    third_cate_id: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.options = options;
    if (options.id) {
      this.setData({
        second_index: "",
        first_cate_id: options.id * 1
      })
    }
    this.setData({ list: [] });


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      nav_flag: false
    });
    app.globalData.isLocationIng = false;
    this.init_loaction();
    this.getCategory();
  },
  getLocationInfo() {
    try {
      this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
        console.log(mapdata, "mapdata====")
        wx.setStorageSync('local-life', mapdata.adcode)
        let city_name = mapdata.address_component.city || '';
        this.setData({
          city_name
        });
        this.data.citycode = mapdata.adcode;
        this.data.point.lng = e.lng;
        this.data.point.lat = e.lat;
        this.getData();
      });
    } catch (e) {
      console.log(e, "e============");
      this.getData();
    }
  },
  init_loaction() {
    let address_point = wx.getStorageSync("address-point");
    if (this.data.options.cityId || this.data.options.city) {
      wx.setStorageSync('local-life', this.data.options.cityId)
      this.setData({
        city_name: this.data.options.city
      });
      if (address_point) {
        this.data.point.lng = address_point.point.lng;
        this.data.point.lat = address_point.point.lat;
      }
      this.data.citycode = this.data.options.cityId;

      this.getData();
    } else if (address_point) {
      wx.setStorageSync('local-life', address_point.adcode)
      let city_name = address_point.city
      this.setData({
        city_name
      });
      this.data.citycode = address_point.adcode;
      this.data.point.lng = address_point.point.lng;
      this.data.point.lat = address_point.point.lat;

      this.getData();
    }
    //  else {
    //   this.getLocationInfo();
    // }
  },
  navHome: function () {
    wx.navigateTo({
      url: '/packageI/citypickerPage/citypickerPage?plu=local_life&path=search'
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.page >= this.data.total_page) return;
    let page = this.data.page + 1;
    this.getData(page);

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  tab(e) {
    console.log(e, "e====");
    let category_name = e.currentTarget.dataset.item.name;
    let first_index = e.currentTarget.dataset.index;
    this.setData({
      nav_flag: false,
      category_name,
      first_index
    })
  },
  toggle(e) {
    let category_name = e.currentTarget.dataset.name;
    let index = e.currentTarget.dataset.index;
    let level = e.currentTarget.dataset.level;
    let cate_id = e.currentTarget.dataset.id * 1;
    if (level == 2) {
      this.data.first_cate_id = cate_id;
    } else if (level == 3) {
      this.data.second_cate_id = cate_id;
    } else {
      this.data.third_cate_id = cate_id;
    }
    if (level !== "4") {
      if (level == 2) {
        this.setData({
          category_name,
          first_index: index,
          second_index: ""
        })
      } else {
        this.setData({
          three_index: "",
          second_index: index
        })
      }
      if(this.data.cate_level == 2&&level==3){
        this.getData();
        this.setData({
          list: [],
          nav_flag: false
        });
        return;
      }
      this.getCategory(level, cate_id);
    } else {
      this.setData({
        category_name,
        list: [],
        three_index: index,
        first_cate_id: cate_id,
        nav_flag: false
      });
      this.getData();
    }
  },
  getCategory(level = 1, id = "") {
    let json = {};
    if (level !== 1 && id !== '') {
      json.parent_id = id;
    }
    app._getNetWork({
      url: app.getNetAddresss("plugin.local-life.api.category.index"),
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let data = res.data.cate;
          this.data.cate_level = res.data.cate_level;
          if (level == 1) {
            this.setData({category_list: data});
            if (data && data.length !== 0 && this.data.options.id) {
              let index = data.findIndex(item => item.id == this.data.options.id);
              console.log(index,'index===',this.data.options.id);
              if(index!==-1){
                let first_index = index;
                let category_name = data[index].name;
                this.getCategory(2, data[index].id);
                this.setData({
                  first_index,
                  category_name
                })
              }
            
            }
          } else if (level == 2) {
            if (data.length == 0) {
              this.setData({
                list: [],
                nav_flag: false
              });
              this.getData();
            } else {
              this.setData({
                second_list: data
              });
            }
          } else if (level == 3) {
            if (data.length == 0) {
              this.setData({
                list: [],
                nav_flag: false
              });
              this.getData();
            } else {
              this.setData({
                three_list: data
              });
            }
          }
        } else {
          app.tips(res.msg)
        }
      },
      fail: function (res) {
        reject(res)
      }
    })
  },

  change(e) {
    let type = e.currentTarget.dataset.num;
    let order_by = '';
    if (this.data.parms[type].order_by == 0) {
      order_by = 1;
    } else if (this.data.parms[type].order_by == 1 && type == this.data.sort_by) {
      order_by = 2;
    } else {
      order_by = 1;
    }
    this.data.parms[type].order_by = order_by;
    this.setData({
      list: [],
      sort_by: type,
      parms: this.data.parms
    });
    this.getData();
  },
  distance() {
    this.data.search_type = 1;
    let limit_1km = this.data.limit_1km == 1 ? 0 : 1;
    this.setData({
      list: [],
      search_type:1,
      limit_1km
    })
    this.getData();
  },
  popup_handle() {
    this.setData({
      nav_flag: !this.data.nav_flag
    })
  },
  search() {
    this.setData({
      list: []
    });
    this.getData();
  },
  getData(page = 1) {
    let json = {
      limit_1km: this.data.limit_1km,
      keyword:this.data.keywords
    };
    if (this.data.search_type && this.data.search_type !== 1) {
      let order_by = this.data.parms[this.data.sort_by].order_by;
      json.search_direct = order_by == 1 ? 'asc' : 'desc';
    }
    if(this.data.first_cate_id){
      json.first_cate_id = this.data.first_cate_id
    }
    if(this.data.second_cate_id){
      json.second_cate_id = this.data.second_cate_id
    }
    if(this.data.third_cate_id){
      json.third_cate_id = this.data.third_cate_id
    }
    
    if (this.data.search_type) {
      json.search_type = this.data.search_type;
    }
    let address_point = wx.getStorageSync("address-point");
    if (this.data.point.lat || (address_point && this.data.city_name == address_point.city)) {
      let latitude = '';
      let longitude = '';
      if (this.data.city_name == address_point.city) {
        latitude = address_point.point.lat * 1;
        longitude = address_point.point.lng * 1;
      } else {
        latitude = this.data.point.lat * 1;
        longitude = this.data.point.lng * 1;
      }
      json.latitude = latitude;
      json.longitude = longitude;
    }

    if (this.data.citycode) {
      let city_id = (this.data.options.city?(wx.getStorageSync('local_life_code')||this.data.options.cityId):this.data.citycode)+'';
      let _city = city_id.slice(0,-2) + '00';//市的city_id
      json.city_id = _city
    }
    let _json = {
      page,
      'search': json
    }
    app._postNetWork({
      url: app.getNetAddresss('plugin.local-life.api.goods.index'),
      data: _json,
      success: resdata => {
        let {
          result,
          data,
          msg
        } = resdata.data;
        if (result) {
          this.data.page = data.current_page;
          this.data.total_page = data.last_page;
          if (data.data && data.data.length !== 0) {
            let list = []
            if(data.current_page==1){
              list = data.data;
            }else{
              list = this.data.list.concat(data.data);
            }
            this.setData({list})
          }
        } else {
          app.tips(msg);
        }
      }
    })
  },
  input_handle(e) {
    this.setData({
      keywords: e.detail.value
    });
  }
})